//
//  ClassExtension.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/19.
//

import Foundation

// MARK: - UIViewController相关
extension UIViewController {
    
    // 定义闭包类型
    typealias SetNavBarAppearenceBlock = (UINavigationBar?, UINavigationBarAppearance?) -> Void
    
    static func loadFromXib() -> UIViewController {
        // 获取当前类的名称
        let className = String(describing: self)
        // 从 XIB 文件加载视图控制器
        let vc = self.init(nibName: className, bundle: nil)
        return vc
    }
    
    func customNavBarAppearance(barTintColor: UIColor?, titleColor: UIColor?, hideLine: Bool = true, customConfigBlock: SetNavBarAppearenceBlock? = nil) {
//        if (barTintColor != nil) || (titleColor != nil) {
            
            var navBar = navigationController?.navigationBar
            if let naVc = self as? UINavigationController {
                navBar = naVc.navigationBar
            }
            if #available(iOS 13.0, *) {
                let appearance = UINavigationBarAppearance()
                if let barTintColor = barTintColor {
                    appearance.backgroundColor = barTintColor
                }
                if let titleColor = titleColor {
                    appearance.titleTextAttributes = [.foregroundColor: titleColor]
                    appearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
                }
                if hideLine {
                    appearance.shadowColor = .clear
                }
                
                if let customConfigBlock = customConfigBlock {
                    customConfigBlock(navBar, appearance)
                }
                
                navBar?.standardAppearance = appearance
                navBar?.scrollEdgeAppearance = appearance
                navBar?.compactAppearance = appearance
            } else {
                if let barTintColor = barTintColor {
                    navBar?.barTintColor = barTintColor
                }
                if let titleColor = titleColor {
                    navBar?.titleTextAttributes = [.foregroundColor: titleColor]
                }
                if hideLine {
                    //去掉导航栏横线
                    navBar?.setBackgroundImage(UIImage(), for: .default)
                    navBar?.shadowImage = UIImage()
                }
                if let customConfigBlock = customConfigBlock {
                    customConfigBlock(navBar, nil)
                }
            }
//        }
    }
    
    func resetNavBarDefaultStyle() {
        var navBar = navigationController?.navigationBar
        if let naVc = self as? UINavigationController {
            navBar = naVc.navigationBar
        }
        guard let navBar = navBar else { return }
        // 1. 创建默认外观配置
        let defaultAppearance = UINavigationBarAppearance()
        defaultAppearance.configureWithTransparentBackground()
        // 2. 应用默认设置
        navBar.standardAppearance = defaultAppearance
        navBar.scrollEdgeAppearance = defaultAppearance
        navBar.compactAppearance = defaultAppearance
        // 3. 重置按钮颜色
        navBar.tintColor = nil 
        // 4. 重置其他自定义属性
        navBar.isTranslucent = true
        navBar.setBackgroundImage(nil, for: .default)
        navBar.shadowImage = nil
    }
    func switchRootVc(vc: UIViewController) {
        guard let window = self.view.window ?? (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window else {
            return
        }
        window.rootViewController = vc
        UIView.transition(with: window,
                          duration: 0.3,
                          options: .transitionFlipFromLeft,
                          animations: nil,
                          completion: nil)
    }
    /// 回到登录页面
    func switchLoginVc() {
        let vc = KLMNavigationController(rootViewController: KLMCodeLoginController())
        switchRootVc(vc: vc)
    }
    
    static func switchLoginVc() {
        guard let window = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window else {
            return
        }
        let vc = KLMNavigationController(rootViewController: KLMCodeLoginController())
        window.rootViewController = vc
        UIView.transition(with: window,
                          duration: 0.3,
                          options: .transitionFlipFromLeft,
                          animations: nil,
                          completion: nil)
    }
    
    func modalVc(vc: UIViewController, animated: Bool = true) {
        vc.modalPresentationStyle = .overCurrentContext
        vc.modalTransitionStyle = .crossDissolve
        present(vc, animated: true)
    }
    
    func presentActionSheet(title: String? = nil, message: String? = nil, actions: [UIAlertAction]) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
        for action in actions {
            alertController.addAction(action)
        }
        // 处理 iPad 上的弹出框显示问题
        if let popoverController = alertController.popoverPresentationController {
            popoverController.sourceView = view
            popoverController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popoverController.permittedArrowDirections = []
        }
        present(alertController, animated: true, completion: nil)
    }
    /// 弹出系统分享控件
    /// - Parameters:
    ///   - activityItems: 要分享的内容（如文本、图片、URL等）
    ///   - excludedActivityTypes: 需要排除的分享类型（如 AirDrop、保存到相册等）
    ///   - completion: 分享完成的回调
    func presentSystemShare(
        activityItems: [Any],
        excludedActivityTypes: [UIActivity.ActivityType]? = nil,
        completion: ((Bool, UIActivity.ActivityType?) -> Void)? = nil
    ) {
        // 创建分享控制器
        let activityVC = UIActivityViewController(
            activityItems: activityItems,
            applicationActivities: nil
        )
        
        // 排除不需要的分享类型
        activityVC.excludedActivityTypes = excludedActivityTypes
        
        // 设置分享完成的回调
        activityVC.completionWithItemsHandler = { activityType, completed, _, error in
            completion?(completed, activityType)
            if let error = error {
                print("分享失败：\(error.localizedDescription)")
            }
        }
        
        // 适配 iPad（必须指定弹出位置）
        if let popoverController = activityVC.popoverPresentationController {
            popoverController.sourceView = self.view
            popoverController.sourceRect = CGRect(
                x: self.view.bounds.midX,
                y: self.view.bounds.midY,
                width: 0,
                height: 0
            )
            popoverController.permittedArrowDirections = [] // 隐藏箭头
        }
        
        // 弹出分享控制器
        DispatchQueue.main.async {
            self.present(activityVC, animated: true)
        }
    }
    
}
// MARK: - UIView相关
extension UIView {
//    func gradientColor(startColor: UIColor, endColor: UIColor, startPoint: CGPoint = CGPoint(x: 0.0, y: 0.0), endPoint: CGPoint = CGPoint(x: 1.0, y: 1.0)) {
//        let gradientLayer = CAGradientLayer()
//        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
//        gradientLayer.startPoint = startPoint
//        gradientLayer.endPoint = endPoint
//        gradientLayer.frame = bounds
//        
//        // 设置渐变层的圆角和裁剪
//        gradientLayer.cornerRadius = layer.cornerRadius
//        gradientLayer.masksToBounds = true
//        
//        layer.insertSublayer(gradientLayer, at: 0)
//    }
    // MARK: - 从 xib 加载视图view
    static func loadFromNib<T: UIView>(_ nibName: String? = nil) -> T {
        let name = nibName ?? String(describing: self)
        let bundle = Bundle(for: self)
        guard let view = bundle.loadNibNamed(name, owner: nil, options: nil)?.first as? T else {
            return self.init() as! T
        }
        return view
    }
}
// MARK: - UILabel相关
extension UILabel {
    func configStyle(with title: String? = nil, font: UIFont? = nil, titleColor: UIColor? = nil) -> Void {
        if let title = title {
            text = title
        }
        if let font = font {
            self.font = font
        }
        if let color = titleColor {
            textColor = color
        }
    }
}
// MARK: - 按钮相关
extension UIButton {
    func configStyle(with title: String? = nil, font: UIFont? = nil, titleColor: UIColor? = nil, image: String? = "", bgImage: UIImage? = nil, state: UIControl.State = .normal) -> Void {
        if let title = title {
            setTitle(title, for: state)
        }
        if let font = font {
            titleLabel?.font = font
        }
        if let color = titleColor {
            setTitleColor(color, for: state)
        }
        if let image = image, !image.isEmpty {
            setImage(UIImage(named: image), for: state)
        }
        if let bgImage = bgImage {
            setBackgroundImage(bgImage, for: state)
        }
    }
}
// MARK: - 图片相关
extension UIImage {
    /// 根据颜色创建一张图片
    /// - Parameters:
    ///   - color: 图片的颜色
    ///   - size: 图片的尺寸
    ///   - cornerRadius: 圆角半径（可选，默认为 0，表示无圆角）
    ///   - borderColor: 边框颜色
    ///   - borderWidth: 边框线宽
    /// - Returns: 生成的图片
    static func image(
        withColor color: UIColor,
        size: CGSize,
        cornerRadius: CGFloat = 0,
        borderColor: UIColor? = nil,
        borderWidth: CGFloat = 0,
        shadowColor: UIColor? = nil,          // 新增：阴影颜色
        shadowOffset: CGSize = .zero,         // 新增：阴影偏移
        shadowBlur: CGFloat = 0,              // 新增：阴影模糊半径
        stretch: Bool = true
    ) -> UIImage? {
        let rect = CGRect(origin: .zero, size: size)
        
        let renderer = UIGraphicsImageRenderer(size: size)
        var image = renderer.image { context in
            let cgContext = context.cgContext
            
            // 配置阴影（新增部分）
            if let shadowColor = shadowColor, shadowBlur > 0 {
                cgContext.setShadow(
                    offset: shadowOffset,
                    blur: shadowBlur,
                    color: shadowColor.cgColor
                )
            }
            
            // 绘制路径
            let path = UIBezierPath(
                roundedRect: rect.insetBy(dx: borderWidth/2, dy: borderWidth/2),
                cornerRadius: cornerRadius
            )
            
            // 填充颜色
            color.setFill()
            path.fill()
            
            // 绘制边框
            if let borderColor = borderColor, borderWidth > 0 {
                borderColor.setStroke()
                path.lineWidth = borderWidth
                path.stroke()
            }
        }
        // 处理可拉伸
        if stretch {
            let vPadding = (size.height - cornerRadius)/2
            let hPadding = (size.width - cornerRadius)/2
            let capInsets = UIEdgeInsets(
                top: vPadding,
                left: hPadding,
                bottom: vPadding,
                right: hPadding
            )
            image = image.resizableImage(
                withCapInsets: capInsets,
                resizingMode: .stretch
            )
        }
        return image
    }
    
    static func image(
        withColor color: UIColor? = nil,    // 改为可选，与 gradient 二选一
        gradient: KLMGradient? = nil,          // 新增：渐变配置
        size: CGSize,
        cornerRadius: CGFloat = 0,
        borderColor: UIColor? = nil,
        borderWidth: CGFloat = 0,
        shadowColor: UIColor? = nil,
        shadowOffset: CGSize = .zero,
        shadowBlur: CGFloat = 0,
        stretch: Bool = true
    ) -> UIImage? {
        // 至少需要 color 或 gradient
        guard color != nil || gradient != nil else {
            return nil
        }
        
        let rect = CGRect(origin: .zero, size: size)
        let renderer = UIGraphicsImageRenderer(size: size)
        
        let image = renderer.image { context in
            let cgContext = context.cgContext
            
            // 配置阴影
            if let shadowColor = shadowColor, shadowBlur > 0 {
                cgContext.setShadow(
                    offset: shadowOffset,
                    blur: shadowBlur,
                    color: shadowColor.cgColor
                )
            }
            
            // 填充路径（考虑边框内缩）
            let fillRect = rect.insetBy(dx: borderWidth/2, dy: borderWidth/2)
            let fillPath = UIBezierPath(
                roundedRect: fillRect,
                cornerRadius: cornerRadius
            )
            
            // --- 填充颜色或渐变 ---
            cgContext.saveGState()
            defer { cgContext.restoreGState() }
            
            // 裁剪到填充路径
            fillPath.addClip()
            
            if let gradient = gradient {
                // 处理渐变
                let colors = gradient.colors.map { $0.cgColor }
                let locations = gradient.locations
                
                guard let cgGradient = CGGradient(
                    colorsSpace: CGColorSpaceCreateDeviceRGB(),
                    colors: colors as CFArray,
                    locations: locations
                ) else { return }
                
                // 计算绝对坐标（基于 fillRect）
                let startPoint = CGPoint(
                    x: fillRect.minX + gradient.startPoint.x * fillRect.width,
                    y: fillRect.minY + gradient.startPoint.y * fillRect.height
                )
                let endPoint = CGPoint(
                    x: fillRect.minX + gradient.endPoint.x * fillRect.width,
                    y: fillRect.minY + gradient.endPoint.y * fillRect.height
                )
                
                // 绘制线性渐变
                cgContext.drawLinearGradient(
                    cgGradient,
                    start: startPoint,
                    end: endPoint,
                    options: []
                )
            } else if let color = color {
                // 单色填充
                color.setFill()
                fillPath.fill()
            }
            
            // --- 绘制边框 ---
            if let borderColor = borderColor, borderWidth > 0 {
                // 边框路径（与填充路径一致）
                let borderPath = UIBezierPath(
                    roundedRect: fillRect,
                    cornerRadius: cornerRadius
                )
                
                borderColor.setStroke()
                borderPath.lineWidth = borderWidth
                borderPath.stroke()
            }
        }
        
        // 处理可拉伸
        if stretch {
            let vPadding = (size.height - cornerRadius)/2
            let hPadding = (size.width - cornerRadius)/2
            let capInsets = UIEdgeInsets(
                top: vPadding,
                left: hPadding,
                bottom: vPadding,
                right: hPadding
            )
            return image.resizableImage(
                withCapInsets: capInsets,
                resizingMode: .stretch
            )
        }
        return image
    }
    func croppedImage(
        with radius: CGFloat,
        imgSize: CGSize,
        borderWidth: CGFloat = 0,
        borderColor: UIColor? = nil
    ) -> UIImage? {
        let newSize = imgSize != .zero ? imgSize : size
        let renderer = UIGraphicsImageRenderer(size: newSize)
        return renderer.image { context in
            let rect = CGRect(origin: .zero, size: newSize)
            
            // 应用圆角裁剪并绘制图片
            let path = UIBezierPath(roundedRect: rect, cornerRadius: radius)
            context.cgContext.saveGState()
            path.addClip()
            self.draw(in: rect)
            context.cgContext.restoreGState()
            
            // 绘制边框
            if borderWidth > 0, let borderColor = borderColor {
                // 调整边框矩形以避免被裁剪
                let borderRect = rect.insetBy(dx: borderWidth / 2, dy: borderWidth / 2)
                let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: radius)
                borderColor.setStroke()
                borderPath.lineWidth = borderWidth
                borderPath.stroke()
            }
        }
    }
    func stretchImage(hPadding: CGFloat, vPadding: CGFloat) -> UIImage {
        if size.height < vPadding*2 || size.width < hPadding*2 {
            let left = size.width * 0.43
            let top = size.height * 0.43
            return resizableImage(withCapInsets: UIEdgeInsets(top: top, left: left, bottom: top, right: left), resizingMode: .stretch)
        } else {
            return resizableImage(withCapInsets: UIEdgeInsets(top: vPadding, left: hPadding, bottom: vPadding, right: hPadding), resizingMode: .stretch)
        }
    }
    /// 通过String生成二维码
    static func generateQRImage(QRCodeString: String, logo: UIImage?, size: CGSize = CGSize(width: 50, height: 50)) -> UIImage? {
        guard let data = QRCodeString.data(using: .utf8, allowLossyConversion: false) else {
            return nil
        }
        let imageFilter = CIFilter(name: "CIQRCodeGenerator")
        imageFilter?.setValue(data, forKey: "inputMessage")
        imageFilter?.setValue("H", forKey: "inputCorrectionLevel")
        let ciImage = imageFilter?.outputImage
        
        // 创建颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")
        colorFilter?.setDefaults()
        colorFilter?.setValue(ciImage, forKey: "inputImage")
        colorFilter?.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0")
        colorFilter?.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1")
        
        // 返回二维码图片
        let qrImage = UIImage(ciImage: (colorFilter?.outputImage)!)
        let imageRect = size.width > size.height ?
            CGRect(x: (size.width - size.height) / 2, y: 0, width: size.height, height: size.height) :
            CGRect(x: 0, y: (size.height - size.width) / 2, width: size.width, height: size.width)
        UIGraphicsBeginImageContextWithOptions(imageRect.size, false, UIScreen.main.scale)
        defer {
            UIGraphicsEndImageContext()
        }
        qrImage.draw(in: imageRect)
        if logo != nil {
            let logoSize = size.width > size.height ?
                CGSize(width: size.height * 0.25, height: size.height * 0.25) :
                CGSize(width: size.width * 0.25, height: size.width * 0.25)
            logo?.draw(in: CGRect(x: (imageRect.size.width - logoSize.width) / 2, y: (imageRect.size.height - logoSize.height) / 2, width: logoSize.width, height: logoSize.height))
        }
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
    

// MARK: - 字体相关
extension UIFont {
    
    convenience init?(safeName: String, size: CGFloat) {
        if UIFont(name: safeName, size: size) != nil {
            self.init(name: safeName, size: size)
        } else {
            print("不生效的字体：", safeName)
            var systemFont = UIFont.systemFont(ofSize: size)
            if safeName.starts(with: "PingFangSC-"), !safeName.contains("Regular") {
                systemFont = UIFont.boldSystemFont(ofSize: size)
            }
            let systemFontDescriptor = systemFont.fontDescriptor
            self.init(descriptor: systemFontDescriptor, size: size)
        }
    }
}

// MARK: - 日期相关
extension Date {
    static func getRemainingTime(timestamp: String) -> (expired: Bool, remain: String) {
        
        if let time = Double(timestamp) {
            // 根据时间戳创建过期日期
            let expirationDate = Date(timeIntervalSince1970: time)
            // 获取当前日期
            let currentDate = Date()
            // 计算两个日期之间的时间间隔（以秒为单位）
            let timeInterval = expirationDate.timeIntervalSince(currentDate)
            // 如果时间间隔小于等于 0，说明已过期
            if timeInterval <= 0 {
                return (true, "邀请失效")
            }
            // 计算剩余天数
            let remainingDays = timeInterval / (60 * 60 * 24)
            if remainingDays >= 1 {
                // 若剩余天数大于等于 1，则向上取整返回天数
                return (false, "\(Int(ceil(remainingDays))) 天")
            }
            // 计算剩余小时数
            let remainingHours = timeInterval / (60 * 60)
            // 若剩余小时数大于 0，则向上取整返回小时数
            return (false, "\(Int(ceil(remainingHours))) 小时")
        }
        return (false, "")
    }
}

// MARK: - 通知相关
extension NotificationCenter {
    /// 广播消息
    static func post(_ name: NSNotification.Name, userInfo: [AnyHashable : Any]? = nil) {
        self.default.post(name: name, object: nil, userInfo: userInfo)
    }
}


// MARK: - 编码相关
extension Encodable {
    /// 将结构体对象转为字典
    func toDictionary() -> [String: Any]? {
        guard let data = try? JSONEncoder().encode(self) else { return nil }
        guard let dict = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { return nil }
        return dict
    }
    
    /// 获取结构体对象的所有属性名
    func propertyNames() -> [String] {
        let mirror = Mirror(reflecting: self)
        return mirror.children.compactMap { $0.label }
    }
}
